#include "file_image.h"
#include "auxiliaryfunction.h"

#include <QImage>
#include <QtEndian>
#include <QFile>
#include <cmath>
//test
#include <QDebug>

FileImage::FileImage()
{

}

FileImage::~FileImage()
{

}

int FileImage::setImageBits(unsigned char bits)
{
    image_bits_ = bits;
    return IMAGE_OK;
}

unsigned char FileImage::getImageBits() const
{
    return image_bits_;
}

int FileImage::setImageSavePosition(unsigned char position)
{
    image_save_position_ = position;
    return IMAGE_OK;
}

unsigned char FileImage::getImageSavePosition() const
{
    return image_save_position_;
}

int FileImage::imageSave(const unsigned char *image_pointer)
{

    image_data_queue_.enqueue(QByteArray(reinterpret_cast<const char*>(image_pointer), IMAGE_PER_LINE_BYTES*IMAGE_HEIGHT));

    addAdditionalImageInformation();

    return IMAGE_OK;
}

int FileImage::setImageAuxiliaryInformation(QByteArray image_message)
{
    image_auxiliary_data_queue_.enqueue(image_message);

    return IMAGE_OK;
}

int FileImage::addAdditionalImageInformation()
{
    while (!image_auxiliary_data_queue_.isEmpty() && !image_data_queue_.isEmpty()) {
        QByteArray iamge_data = image_data_queue_.dequeue();
        QByteArray image_auxiliary_data = image_auxiliary_data_queue_.dequeue();
        //对拼接的数据剪切下设备号并拼接文件名
        unsigned int device_number = static_cast<unsigned int>(image_auxiliary_data.right(1).at(0));
        image_auxiliary_data.chop(1);
        unsigned int image_count_number = AuxiliaryFunction::ByteArrayToUInt(image_auxiliary_data.right(4));
        image_auxiliary_data.chop(4);


        double latitude = qFromLittleEndian<double>(image_auxiliary_data.constData() + 10);

        double longitude= qFromLittleEndian<double>(image_auxiliary_data.constData() + 18);
        char latitude_flag = 'N';
        char longitude_flag = 'E';
        if(latitude < 0.0){
            latitude = std::abs(latitude);
            latitude_flag = 'S';
        }
        if(longitude < 0.0){
            longitude = std::abs(longitude);
            longitude_flag = 'W';
        }

        QString file_name = QString("AFC02_%1%2%3%4%5%6_%7%8%9%10_%11%12_%13.raw")
                .arg(image_auxiliary_data[4]+2000).arg(image_auxiliary_data[5],2,10,QChar('0')).arg(image_auxiliary_data[6],2,10,QChar('0'))
                .arg(image_auxiliary_data[7],2,10,QChar('0')).arg(image_auxiliary_data[8],2,10,QChar('0')).arg(image_auxiliary_data[9],2,10,QChar('0'))
                .arg(latitude, 0, 'f', 4).arg(latitude_flag).arg(longitude, 0, 'f', 4).arg(longitude_flag)
                .arg(qFromLittleEndian<quint32>(image_auxiliary_data.constData()),5,10,QChar('0'))
                .arg(image_count_number,5,10,QChar('0'))
                .arg(device_number,2,10,QChar('0'));

        if(TwelveBit == image_bits_){
            QByteArray append_data;
            append_data.resize(IMAGE_PER_LINE_BYTES);
            append_data.fill(0); //全部写0
            append_data.replace(0,image_auxiliary_data.size(),image_auxiliary_data); //替换想要添加的内容
            iamge_data.append(append_data);

//            //保存为图像格式
//            QImage all_image(reinterpret_cast<const unsigned char*>(iamge_data.data()),IMAGE_WIDTCH,IMAGE_HEIGHT+1,QImage::Format_Grayscale16);
            selectImageSaveLocation(iamge_data, file_name);
        }else if(EightBit == image_bits_){
            int total_bytes = IMAGE_WIDTCH * IMAGE_HEIGHT;
            QByteArray result(total_bytes, Qt::Uninitialized);
            char *dst = result.data();
            char *src = iamge_data.data();
            for (int i = 0; i < total_bytes; ++i) {
                dst[i] = src[i * 2 + 1];
            }

            QByteArray append_data;
            append_data.resize(IMAGE_WIDTCH);
            append_data.fill(0); //全部写0
            append_data.replace(0,image_auxiliary_data.size(),image_auxiliary_data); //替换想要添加的内容
            result.append(append_data);

//            QImage all_image(reinterpret_cast<const unsigned char*>(result.data()),IMAGE_WIDTCH,IMAGE_HEIGHT+1,QImage::Format_Grayscale8);
            selectImageSaveLocation(result, file_name);
        }else{
            return IMAGE_ERR;
        }
    }
    return IMAGE_OK;
}

int FileImage::selectImageSaveLocation(QImage image_data, QString image_name)
{
    if(InternalStorage == image_save_position_){
        image_data.save(INTERNAL_STORAGE_PATH + image_name);
    }else if(ExternalStorage == image_save_position_){
        image_data.save(EXTERNAL_STORAGE_PATH + image_name);
    }else if(All == image_save_position_){
        image_data.save(INTERNAL_STORAGE_PATH + image_name);
        image_data.save(EXTERNAL_STORAGE_PATH + image_name);
    }else{
        return IMAGE_ERR;
    }

    return IMAGE_OK;
}

int FileImage::selectImageSaveLocation(QByteArray image_data, QString image_name)
{
    if(InternalStorage == image_save_position_){
        QFile file_in(INTERNAL_STORAGE_PATH + image_name);
        if (file_in.open(QIODevice::WriteOnly)) {
            // 写入数据
            file_in.write(image_data);
            file_in.close(); // 关闭文件
        }
    }else if(ExternalStorage == image_save_position_){
        QFile file_ex(EXTERNAL_STORAGE_PATH + image_name);
        if (file_ex.open(QIODevice::WriteOnly)) {
            // 写入数据
            file_ex.write(image_data);
            file_ex.close(); // 关闭文件
        }
    }else if(All == image_save_position_){
        QFile file_in(INTERNAL_STORAGE_PATH + image_name);
        if (file_in.open(QIODevice::WriteOnly)) {
            // 写入数据
            file_in.write(image_data);
            file_in.close(); // 关闭文件
        }
        QFile file_ex(EXTERNAL_STORAGE_PATH + image_name);
        if (file_ex.open(QIODevice::WriteOnly)) {
            // 写入数据
            file_ex.write(image_data);
            file_ex.close(); // 关闭文件
        }
    }else{
        return IMAGE_ERR;
    }

    return IMAGE_OK;
}
